package com.ssy.lingxi.search.serviceImpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ssy.lingxi.common.constant.CommonConstant;
import com.ssy.lingxi.common.constant.Constants;
import com.ssy.lingxi.common.constant.marketing.ActivityTypeEnum;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.component.redis.service.IRedisStringUtils;
import com.ssy.lingxi.marketing.api.feign.ActivityGoodsControllerFeign;
import com.ssy.lingxi.marketing.api.model.request.GoodsCartRequest;
import com.ssy.lingxi.marketing.api.model.request.GoodsCartSkuItemRequest;
import com.ssy.lingxi.marketing.api.model.response.GoodsCartResponse;
import com.ssy.lingxi.member.merchant.api.feign.inner.MemberLevelRightCreditControllerFeign;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.request.MemberFeignBatchVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.request.MemberFeignUpperMemberVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.request.MemberFeignVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.response.MemberFeignLevelDetailVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.response.MemberFeignRightDetailVO;
import com.ssy.lingxi.order.api.feign.OrderFeignService;
import com.ssy.lingxi.order.api.model.vo.request.MemberAndRoleIdFeignVO;
import com.ssy.lingxi.order.api.model.vo.request.OrderFreeExpressFeignVO;
import com.ssy.lingxi.order.api.model.vo.response.OrderFreeExpressConfigVO;
import com.ssy.lingxi.search.api.model.request.PurchaseCustomerRequest;
import com.ssy.lingxi.search.api.model.request.PurchaseRequest;
import com.ssy.lingxi.search.api.model.request.SimpleIdListRequest;
import com.ssy.lingxi.search.common.PurchaseCommodityTypeEnum;
import com.ssy.lingxi.search.entity.Commodity;
import com.ssy.lingxi.search.entity.CommodityShop;
import com.ssy.lingxi.search.entity.CommodityUnitPricePic;
import com.ssy.lingxi.search.entity.Purchase;
import com.ssy.lingxi.search.model.response.PurchaseCommodityResponse;
import com.ssy.lingxi.search.model.response.PurchaseResponse;
import com.ssy.lingxi.search.model.response.PurchaseUnitPriceAndPicResponse;
import com.ssy.lingxi.search.repository.CommodityRepository;
import com.ssy.lingxi.search.repository.PurchaseRepository;
import com.ssy.lingxi.search.service.ICommodityService;
import com.ssy.lingxi.search.service.IPurchaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 进货单实现类
 * @author jw.chen
 * @version 2.0.0
 * @date 2020/6/22
 */
@Service
public class PurchaseServiceImpl implements IPurchaseService {

    @Resource
    private PurchaseRepository purchaseRepository;

    @Resource
    private CommodityRepository commodityRepository;

    @Resource
    private ICommodityService commodityService;

    @Resource
    private IRedisStringUtils redisStringUtils;

    @Resource
    private MemberLevelRightCreditControllerFeign memberFeign;

    @Resource
    private OrderFeignService orderFeignService;

    @Resource
    private ActivityGoodsControllerFeign activityGoodsControllerFeign;

    @Resource
    private MemberLevelRightCreditControllerFeign memberLevelRightCreditControllerFeign;

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 查询进货单列表
     * @param sysUser               登录用户
     * @param shopId                商城id
     * @param flag                  是否需要查询活动数据
     * @param customerMemberId      代客下单-客户会员id
     * @param customerMemberRoleId  代客下单-客户会员角色id
     * @param orderId               代客下单-订单id
     */
    @Override
    public List<PurchaseResponse> getPurchaseList(UserLoginCacheDTO sysUser, Long shopId, Boolean flag, Long customerMemberId, Long customerMemberRoleId, Long orderId){
        long startTime = System.currentTimeMillis();
        List<PurchaseResponse> purchaseResponseList = new ArrayList<>();
        //查询进货单
        Long memberId = sysUser.getMemberId();
        Long memberRoleId = sysUser.getMemberRoleId();

        List<Purchase> purchaseList;
        //判断是否代客下单
        if(customerMemberId != null && customerMemberId > 0){
            if(orderId != null && orderId > 0){
                purchaseList = purchaseRepository.findByMemberIdAndMemberRoleIdAndShopIdAndCustomerMemberIdAndCustomerMemberRoleIdAndOrderId(memberId, memberRoleId, shopId, customerMemberId, customerMemberRoleId, orderId);
            }else{
                purchaseList = purchaseRepository.findByMemberIdAndMemberRoleIdAndShopIdAndCustomerMemberIdAndCustomerMemberRoleId(memberId, memberRoleId, shopId, customerMemberId, customerMemberRoleId);
            }
        }else{
            purchaseList = purchaseRepository.findByMemberIdAndMemberRoleIdAndShopId(memberId, memberRoleId, shopId);
        }

        long dateBaseEndTime = System.currentTimeMillis();
        if(!CollectionUtils.isEmpty(purchaseList)){
            //定义临时变量
            List<Long> commoditySkuIdList = new ArrayList<>();
            List<MemberFeignUpperMemberVO> memberFeignUpperMemberVOList = new ArrayList<>();
            List<GoodsCartSkuItemRequest> goodsCartSkuItemRequestList = new ArrayList<>();
            List<MemberAndRoleIdFeignVO> memberAndRoleIdFeignVOList = new ArrayList<>();

            //查询登录用户的所有上级对应的会员等级
            Map<String, Integer> memberLevelMap = new HashMap<>();
            MemberFeignVO memberFeignVO = new MemberFeignVO();
            //判断是否代客下单
            if(customerMemberId != null && customerMemberId > 0){
                memberFeignVO.setMemberId(customerMemberId);
                memberFeignVO.setRoleId(customerMemberRoleId);
            }else{
                memberFeignVO.setMemberId(memberId);
                memberFeignVO.setRoleId(memberRoleId);
            }
            Wrapper<List<MemberFeignLevelDetailVO>> subMemberLevels = memberLevelRightCreditControllerFeign.findSubMemberLevels(memberFeignVO);
            if(subMemberLevels != null && ResponseCode.SUCCESS.getCode() == subMemberLevels.getCode()){
                List<MemberFeignLevelDetailVO> data = subMemberLevels.getData();
                if(!CollectionUtils.isEmpty(data)){
                    data.stream().filter(memberFeignLevelDetailVO -> memberFeignLevelDetailVO.getRelType() == 1).forEach(memberFeignLevelDetailVO -> {
                        Long upperMemberId = memberFeignLevelDetailVO.getUpperMemberId();
                        Long upperRoleId = memberFeignLevelDetailVO.getUpperRoleId();
                        Integer level = memberFeignLevelDetailVO.getLevel();
                        memberLevelMap.put(upperMemberId + Constants.UNDERLINE_STR + upperRoleId, level);
                    });
                }
            }

            MemberFeignBatchVO memberFeignBatchVO = new MemberFeignBatchVO();
            //判断是否代客下单
            if(customerMemberId != null && customerMemberId > 0){
                memberFeignBatchVO.setMemberId(customerMemberId);
                memberFeignBatchVO.setRoleId(customerMemberRoleId);
            }else{
                memberFeignBatchVO.setMemberId(memberId);
                memberFeignBatchVO.setRoleId(memberRoleId);
            }
            //组装redis键值格式
            List<HashMap<String, String[]>> keyFieldList = purchaseList.stream().map(purchase -> {
                Long commodityUnitPriceId = purchase.getCommodityUnitPriceId();
                Integer purchaseCommodityType = purchase.getPurchaseCommodityType();

                //记录所有skuId，用于查询商品活动信息
                GoodsCartSkuItemRequest goodsCartSkuItemRequest = new GoodsCartSkuItemRequest();
                goodsCartSkuItemRequest.setSkuId(commodityUnitPriceId);
                if(purchaseCommodityType != null && purchaseCommodityType.equals(PurchaseCommodityTypeEnum.SET_MEAL.getCode())){
                    goodsCartSkuItemRequest.setActivityType(ActivityTypeEnum.SET_MEAL.getCode());
                    goodsCartSkuItemRequest.setGroupNo(purchase.getSetMealId().intValue());
                    goodsCartSkuItemRequest.setParentSkuId(purchase.getParentSkuId());
                }else if(purchaseCommodityType != null && purchaseCommodityType.equals(PurchaseCommodityTypeEnum.EXCHANGE.getCode())){
                    goodsCartSkuItemRequest.setActivityType(ActivityTypeEnum.SWAP.getCode());
                    goodsCartSkuItemRequest.setParentSkuId(purchase.getParentSkuId());
                }
                goodsCartSkuItemRequest.setIsMain(purchase.getIsMain());
                goodsCartSkuItemRequestList.add(goodsCartSkuItemRequest);

                //记录所有skuId，用于查询商品
                commoditySkuIdList.add(commodityUnitPriceId);
                //缓存查询key
                String key = CommonConstant.FREIGHT_SPACE_REDIS_KEY + shopId + "_" + commodityUnitPriceId;
                HashMap<String, String[]> map = new HashMap<>();
                //判断是否代客下单
                if(customerMemberId != null && customerMemberId > 0){
                    map.put(key, new String[]{String.valueOf(customerMemberId), CommonConstant.FREIGHT_All});
                }else{
                    map.put(key, new String[]{String.valueOf(memberId), CommonConstant.FREIGHT_All});
                }
                return map;
            }).collect(Collectors.toList());
            long dataTime = System.currentTimeMillis();

            //批量查询商品信息
            HashMap<Long, Commodity> commodityHashMap = new HashMap<>();
            List<Commodity> commodityList = commodityRepository.findByUnitPricePicListIdIn(commoditySkuIdList);
            commodityList.forEach(commodity -> {
                List<CommodityUnitPricePic> unitPricePicList = commodity.getUnitPricePicList();
                unitPricePicList.forEach(unitPricePic -> commodityHashMap.put(unitPricePic.getId(), commodity));

                //记录所有供应商信息，用于查询价格权益
                MemberFeignUpperMemberVO memberFeignUpperMemberVO = new MemberFeignUpperMemberVO();
                memberFeignUpperMemberVO.setUpperMemberId(commodity.getMemberId());
                memberFeignUpperMemberVO.setUpperRoleId(commodity.getMemberRoleId());
                if(!memberFeignUpperMemberVOList.contains(memberFeignUpperMemberVO)){
                    memberFeignUpperMemberVOList.add(memberFeignUpperMemberVO);
                }

                //记录所有供应商信息，用于查询商品是否满额包邮
                MemberAndRoleIdFeignVO memberAndRoleIdFeignVO = new MemberAndRoleIdFeignVO();
                memberAndRoleIdFeignVO.setMemberId(commodity.getMemberId());
                memberAndRoleIdFeignVO.setRoleId(commodity.getMemberRoleId());
                if(!memberAndRoleIdFeignVOList.contains(memberAndRoleIdFeignVO)){
                    memberAndRoleIdFeignVOList.add(memberAndRoleIdFeignVO);
                }
            });

            long esEndTime = System.currentTimeMillis();

            //批量查询商品活动信息
            Map<String, GoodsCartResponse> goodsCartResponseHashMap = new HashMap<>();
            try{
                if(flag){
                    GoodsCartRequest goodsCartRequest = new GoodsCartRequest();
                    //判断是否代客下单
                    if(customerMemberId != null && customerMemberId > 0){
                        goodsCartRequest.setMemberId(customerMemberId);
                        goodsCartRequest.setRoleId(customerMemberRoleId);
                    }else{
                        goodsCartRequest.setMemberId(memberId);
                        goodsCartRequest.setRoleId(memberRoleId);
                    }
                    goodsCartRequest.setShopId(shopId);
                    goodsCartRequest.setSkuList(goodsCartSkuItemRequestList);
                    Wrapper<List<GoodsCartResponse>> activityGoodsCart = activityGoodsControllerFeign.listActivityGoodsCart(goodsCartRequest);
                    if(activityGoodsCart != null && activityGoodsCart.getCode() == ResponseCode.SUCCESS.getCode()){
                        List<GoodsCartResponse> data = activityGoodsCart.getData();
                        if(!CollectionUtils.isEmpty(data)){
                            for (GoodsCartResponse goodsCartResponse : data) {
                                Integer groupNo = null;
                                Long skuId = goodsCartResponse.getSkuId();
                                Integer activityType = goodsCartResponse.getActivityType();
                                if(ActivityTypeEnum.SET_MEAL.getCode().equals(activityType)){
                                    activityType = PurchaseCommodityTypeEnum.SET_MEAL.getCode();
                                    groupNo = goodsCartResponse.getGroupNo();
                                }else if(ActivityTypeEnum.SWAP.getCode().equals(activityType)){
                                    activityType = PurchaseCommodityTypeEnum.EXCHANGE.getCode();
                                }else{
                                    activityType = null;
                                }
                                Boolean isMain = goodsCartResponse.getIsMain();
                                Long parentSkuId = goodsCartResponse.getParentSkuId();
                                String key = skuId + "_" + activityType + "_" + isMain + "_" + parentSkuId + "_" + groupNo;
                                goodsCartResponseHashMap.put(key, goodsCartResponse);
                            }
                        }
                    }
                    log.info("批量查询商品活动信息，参数{}", JSONUtil.toJsonStr(goodsCartRequest));
                    log.info("批量查询商品活动信息，返回值{}", JSONUtil.toJsonStr(activityGoodsCart));
                }
            }catch (Exception e){
                e.printStackTrace();
            }

            long goodsCartEndTime = System.currentTimeMillis();

            //查询价格权益
            memberFeignBatchVO.setUpperMembers(memberFeignUpperMemberVOList);
            HashMap<String, BigDecimal> memberMap = new HashMap<>();
            try{
                Wrapper<List<MemberFeignRightDetailVO>> listWrapper = memberFeign.batchMemberPriceRight(memberFeignBatchVO);
                if(listWrapper != null && listWrapper.getCode() == ResponseCode.SUCCESS.getCode()){
                    List<MemberFeignRightDetailVO> data = listWrapper.getData();
                    data.forEach(memberFeignRightDetailVO -> {
                        String member = memberFeignRightDetailVO.getUpperMemberId() + "_" + memberFeignRightDetailVO.getUpperRoleId();
                        memberMap.put(member, memberFeignRightDetailVO.getParameter());
                    });
                }
            }catch (Exception e){
                e.printStackTrace();
            }

            //查询供应商商品是否满额包邮
            OrderFreeExpressFeignVO orderFreeExpressFeignVO = new OrderFreeExpressFeignVO();
            orderFreeExpressFeignVO.setItemList(memberAndRoleIdFeignVOList);
            HashMap<String, BigDecimal> orderFreeExpressMap = new HashMap<>();
            try{
                Wrapper<List<OrderFreeExpressConfigVO>> listWrapper = orderFeignService.getOrderFreeExpressConfigList(orderFreeExpressFeignVO);
                if(listWrapper != null && listWrapper.getCode() == ResponseCode.SUCCESS.getCode()){
                    List<OrderFreeExpressConfigVO> data = listWrapper.getData();
                    data.forEach(orderFreeExpressConfigVO -> {
                        String member = orderFreeExpressConfigVO.getMemberId() + "_" + orderFreeExpressConfigVO.getRoleId();
                        orderFreeExpressMap.put(member, orderFreeExpressConfigVO.getOrderAmount());
                    });
                }
            }catch (Exception e){
                e.printStackTrace();
            }

            long memberEndTime = System.currentTimeMillis();

            //获取库存数据并赋值给每个进货单
            List<Object> resultList = redisStringUtils.hMGetBatch(keyFieldList, Constants.REDIS_PRODUCT_INDEX);
            for(int i = 0; i < purchaseList.size(); i++){
                PurchaseResponse purchaseResponse = new PurchaseResponse();
                Purchase purchase = purchaseList.get(i);
                BeanUtil.copyProperties(purchase, purchaseResponse);
                //计算当前商品的库存数
                List<String> stockList = (List<String>)resultList.get(i);
                if(stockList != null && !stockList.isEmpty()){
                    List<String> collect = stockList.stream().filter(StrUtil::isNotEmpty).collect(Collectors.toList());
                    if(!collect.isEmpty()){
                        Double stockCount = collect.stream().map(Double::parseDouble).reduce(Double::sum).get();
                        purchaseResponse.setStockCount(stockCount);
                    }
                }
                Long commodityUnitPriceId = purchase.getCommodityUnitPriceId();
                Commodity commodity = commodityHashMap.get(commodityUnitPriceId);
                if(commodity != null){
                    Integer memberLevel = memberLevelMap.get(commodity.getMemberId() + Constants.UNDERLINE_STR + commodity.getMemberRoleId());
                    //判断是否代客下单
                    if(customerMemberId != null && customerMemberId > 0){
                        //根据价格策略设置价格
                        commodityService.setCommodityPrice(commodity, shopId, customerMemberId, customerMemberRoleId, memberLevel == null ? 0 : memberLevel);
                    }else{
                        //根据价格策略设置价格
                        commodityService.setCommodityPrice(commodity, shopId, memberId, memberRoleId, memberLevel == null ? 0 : memberLevel);
                    }
                    //获取sku信息
                    commodity.getUnitPricePicList().forEach(unitPricePic -> {
                        Long unitPricePicId = unitPricePic.getId();
                        if(unitPricePicId.longValue() == commodityUnitPriceId.longValue()){
                            PurchaseUnitPriceAndPicResponse purchaseUnitPriceAndPicResponse = new PurchaseUnitPriceAndPicResponse();
                            BeanUtil.copyProperties(unitPricePic, purchaseUnitPriceAndPicResponse);
                            PurchaseCommodityResponse purchaseCommodityResponse = new PurchaseCommodityResponse();
                            BeanUtil.copyProperties(commodity, purchaseCommodityResponse);
                            purchaseUnitPriceAndPicResponse.setCommodity(purchaseCommodityResponse);
                            purchaseResponse.setCommodityUnitPrice(purchaseUnitPriceAndPicResponse);
                        }
                    });
                    //判断商品是否上架
                    List<CommodityShop> commodityShopList = commodity.getCommodityShopList();
                    if(commodityShopList != null && commodityShopList.size() > 0){
                        List<Long> commodityShopIdList = commodityShopList.stream().map(CommodityShop::getShopId).collect(Collectors.toList());
                        if(commodityShopIdList.size() > 0){
                            purchaseResponse.setIsPublish(commodityShopIdList.contains(shopId));
                        }
                    }

                    //获取价格权益
                    BigDecimal bigDecimal = memberMap.get(commodity.getMemberId() + "_" + commodity.getMemberRoleId());
                    if(bigDecimal != null && bigDecimal.compareTo(BigDecimal.ZERO) > 0){
                        purchaseResponse.setParameter(bigDecimal);
                    }else{
                        purchaseResponse.setParameter(BigDecimal.valueOf(1L));
                    }

                    //获取供应商商品是否满额包邮
                    BigDecimal orderAmount = orderFreeExpressMap.get(commodity.getMemberId() + "_" + commodity.getMemberRoleId());
                    if(orderAmount != null && orderAmount.compareTo(BigDecimal.ZERO) > 0){
                        purchaseResponse.setOrderAmount(orderAmount);
                    }

                    //获取活动相关信息
                    Long setMealId = null;
                    Integer purchaseCommodityType = purchase.getPurchaseCommodityType();
                    Boolean isMain = purchase.getIsMain();
                    Long parentSkuId = purchase.getParentSkuId();
                    if(PurchaseCommodityTypeEnum.SET_MEAL.getCode().equals(purchaseCommodityType)){
                        setMealId = purchase.getSetMealId();
                        purchaseCommodityType = PurchaseCommodityTypeEnum.SET_MEAL.getCode();
                    }else{
                        if(!PurchaseCommodityTypeEnum.EXCHANGE.getCode().equals(purchaseCommodityType)){
                            purchaseCommodityType = null;
                        }
                    }
                    String key = commodityUnitPriceId + "_" + purchaseCommodityType + "_" + isMain + "_" + parentSkuId + "_" + setMealId;
                    log.info("批量查询商品活动信息，key{}", key);
                    purchaseResponse.setGoodsCartResponse(goodsCartResponseHashMap.get(key));

                    purchaseResponseList.add(purchaseResponse);
                }
            }
            long redisEndTime = System.currentTimeMillis();

            log.info("查询进货单接口，用时时长分别为：");
            log.info("数据库时长：{}秒", (dateBaseEndTime - startTime) * 0.001);
            log.info("数组组装时长：{}秒", (dataTime - dateBaseEndTime) * 0.001);
            log.info("es时长：{}秒", (esEndTime - dataTime) * 0.001);
            log.info("商品活动时长：{}秒", (goodsCartEndTime - dateBaseEndTime) * 0.001);
            log.info("会员价格权益时长：{}秒", (memberEndTime - goodsCartEndTime) * 0.001);
            log.info("redis时长：{}秒", (redisEndTime - memberEndTime) * 0.001);
            return purchaseResponseList;
        }else{
            return new ArrayList<>();
        }
    }

    /**
     * 添加/修改进货单
     * @param purchase
     * @return
     */
    @Override
    public Integer saveOrUpdatePurchase(UserLoginCacheDTO sysUser, Purchase purchase){
        Long memberId = sysUser.getMemberId();
        Long memberRoleId = sysUser.getMemberRoleId();
        Long id = purchase.getId();
        Long shopId = purchase.getShopId();
        Long customerMemberId = purchase.getCustomerMemberId();
        Long customerMemberRoleId = purchase.getCustomerMemberRoleId();
        Long orderId = purchase.getOrderId();
        //判断是新增还是修改
        if(id != null && id > 0){
            //验证数据库中是否存在该数据
            Purchase oldPurchase = purchaseRepository.findById(id).orElse(null);
            if(oldPurchase != null){
                Long oldShopId = oldPurchase.getShopId();
                if(shopId.longValue() == oldShopId.longValue()){
                    double count = purchase.getCount();
                    Long commodityUnitPriceId = oldPurchase.getCommodityUnitPriceId();
                    double stock;
                    //判断是否代客下单
                    if(customerMemberId != null && customerMemberId > 0){
                        stock = commodityService.getCommodityStockBySkuId(shopId, customerMemberId, commodityUnitPriceId);
                    }else{
                        stock = commodityService.getCommodityStockBySkuId(shopId, memberId, commodityUnitPriceId);
                    }
                    if(count <= stock){
                        oldPurchase.setCount(count);
                        purchaseRepository.saveAndFlush(oldPurchase);
                        //判断是否代客下单
                        if(customerMemberId != null && customerMemberId > 0){
                            if(orderId != null && orderId > 0){
                                return purchaseRepository.countByMemberIdAndMemberRoleIdAndShopIdAndCustomerMemberIdAndCustomerMemberRoleIdAndOrderId(memberId, memberRoleId, shopId, customerMemberId, customerMemberRoleId, orderId);
                            }else{
                                return purchaseRepository.countByMemberIdAndMemberRoleIdAndShopIdAndCustomerMemberIdAndCustomerMemberRoleId(memberId, memberRoleId, shopId, customerMemberId, customerMemberRoleId);
                            }
                        }else{
                            return purchaseRepository.countByMemberIdAndMemberRoleIdAndShopId(memberId, memberRoleId, shopId);
                        }
                    }else{
                        throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_PASS_STOCK);
                    }
                }
            }
            throw new BusinessException(ResponseCode.PRODUCT_PURCHASE_NOT_EXIST);
        }else{
            //检查商品规格
            Long commodityUnitPriceId = purchase.getCommodityUnitPriceId();
            if(commodityUnitPriceId != null && commodityUnitPriceId > 0){
                Commodity commodity = commodityRepository.findByUnitPricePicListId(commodityUnitPriceId);
                if(commodity != null){
                    //查询库存
                    double stock;
                    //判断是否代客下单
                    if(customerMemberId != null && customerMemberId > 0){
                        stock = commodityService.getCommodityStockBySkuId(shopId, customerMemberId, commodityUnitPriceId);
                    }else{
                        stock = commodityService.getCommodityStockBySkuId(shopId, memberId, commodityUnitPriceId);
                    }
                    Integer purchaseCommodityType = purchase.getPurchaseCommodityType();
                    Purchase oldPurchase;
                    //判断是否代客下单
                    if(customerMemberId != null && customerMemberId > 0){
                        if(orderId != null && orderId > 0){
                            oldPurchase = purchaseRepository.findFirstByMemberIdAndMemberRoleIdAndCommodityUnitPriceIdAndShopIdAndPurchaseCommodityTypeAndCustomerMemberIdAndCustomerMemberRoleIdAndOrderId(memberId, memberRoleId, commodityUnitPriceId, shopId, purchaseCommodityType, customerMemberId, customerMemberRoleId, orderId);
                        }else{
                            oldPurchase = purchaseRepository.findFirstByMemberIdAndMemberRoleIdAndCommodityUnitPriceIdAndShopIdAndPurchaseCommodityTypeAndCustomerMemberIdAndCustomerMemberRoleId(memberId, memberRoleId, commodityUnitPriceId, shopId, purchaseCommodityType, customerMemberId, customerMemberRoleId);
                        }
                    }else{
                        oldPurchase = purchaseRepository.findFirstByMemberIdAndMemberRoleIdAndCommodityUnitPriceIdAndShopIdAndPurchaseCommodityType(memberId, memberRoleId, commodityUnitPriceId, shopId, purchaseCommodityType);
                    }
                    if(oldPurchase != null){
                        double count = oldPurchase.getCount() + purchase.getCount();
                        if(count <= stock) {
                            oldPurchase.setCount(count);
                        }else{
                            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_PASS_STOCK);
                        }
                    }else{
                        Integer purchaseMaxCount = Constants.PURCHASE_MAX_COUNT;
                        Integer existPurchaseCount;
                        //判断是否代客下单
                        if(customerMemberId != null && customerMemberId > 0){
                            if(orderId != null && orderId > 0){
                                existPurchaseCount = purchaseRepository.countByMemberIdAndMemberRoleIdAndShopIdAndCustomerMemberIdAndCustomerMemberRoleIdAndOrderId(memberId, memberRoleId, shopId, customerMemberId, customerMemberRoleId, orderId);
                            }else{
                                existPurchaseCount = purchaseRepository.countByMemberIdAndMemberRoleIdAndShopIdAndCustomerMemberIdAndCustomerMemberRoleId(memberId, memberRoleId, shopId, customerMemberId, customerMemberRoleId);
                            }
                        }else{
                            existPurchaseCount = purchaseRepository.countByMemberIdAndMemberRoleIdAndShopId(memberId, memberRoleId, shopId);
                        }
                        if(existPurchaseCount >= purchaseMaxCount){
                            throw new BusinessException(ResponseCode.PRODUCT_PURCHASE_COUNT_OUT);
                        }

                        double count = purchase.getCount();
                        if(count <= stock) {
                            oldPurchase = new Purchase();
                            //数据库持久化对象
                            oldPurchase.setShopId(shopId);
                            oldPurchase.setCount(purchase.getCount());
                            oldPurchase.setCommodityUnitPriceId(commodityUnitPriceId);
                            oldPurchase.setMemberId(memberId);
                            oldPurchase.setMemberName(sysUser.getCompany());
                            oldPurchase.setMemberRoleId(memberRoleId);
                            oldPurchase.setMemberRoleName(sysUser.getMemberRoleName());
                            oldPurchase.setUserId(sysUser.getUserId());
                            oldPurchase.setUserName(sysUser.getUserName());
                            oldPurchase.setCustomerMemberId(customerMemberId);
                            oldPurchase.setCustomerMemberRoleId(customerMemberRoleId);
                            oldPurchase.setPurchaseCommodityType(purchase.getPurchaseCommodityType());
                            oldPurchase.setOrderId(orderId);
                        }else{
                            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_PASS_STOCK);
                        }
                    }
                    purchaseRepository.saveAndFlush(oldPurchase);
                    return this.getPurchaseCount(sysUser, shopId, customerMemberId, customerMemberRoleId, orderId);
                }else{
                    throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
                }
            }
            throw new BusinessException(ResponseCode.PRODUCT_PURCHASE_UNITPRICE_NOT_EXIST);
        }
    }

    /**
     * 删除进货单
     * @param simpleIdListRequest
     * @return
     */
    @Override
    public String deletePurchase(SimpleIdListRequest simpleIdListRequest) {
        List<Purchase> deletePurchaseList = new ArrayList<>();
        //验证数据库中是否存在该数据
        List<Long> idList = simpleIdListRequest.getIdList();
        List<Purchase> purchaseList = purchaseRepository.findByIdIn(idList);
        if(purchaseList != null && purchaseList.size() == idList.size()){
            purchaseList.forEach(purchase -> {
                //删除主商品，需要把子商品一起删除
                Integer purchaseCommodityType = purchase.getPurchaseCommodityType();
                if(PurchaseCommodityTypeEnum.SET_MEAL.getCode().equals(purchaseCommodityType) || PurchaseCommodityTypeEnum.EXCHANGE.getCode().equals(purchaseCommodityType)){
                    Boolean isMain = purchase.getIsMain();
                    if(isMain != null && isMain){
                        Long userId = purchase.getUserId();
                        Long setMealId = purchase.getSetMealId();
                        Long shopId = purchase.getShopId();
                        List<Purchase> purchaseSetMealList = purchaseRepository.findByUserIdAndSetMealIdAndShopId(userId, setMealId, shopId);
                        purchaseSetMealList.forEach(purchaseSetMeal -> {
                            if(!deletePurchaseList.contains(purchaseSetMeal)){
                                deletePurchaseList.add(purchaseSetMeal);
                            }
                        });
                    }else{
                        deletePurchaseList.add(purchase);
                    }
                }else{
                    deletePurchaseList.add(purchase);
                }
            });
            if(deletePurchaseList.size() > 0){
                purchaseRepository.deleteAll(deletePurchaseList);
                return ResponseCode.SUCCESS.getMessage();
            }
        }
        throw new BusinessException(ResponseCode.PRODUCT_PURCHASE_NOT_EXIST);
    }

    /**
     * 查询进货单数量
     * @param sysUser
     * @return
     */
    @Override
    public Integer getPurchaseCount(UserLoginCacheDTO sysUser, Long shopId, Long customerMemberId, Long customerMemberRoleId, Long orderId) {
        Long memberId = sysUser.getMemberId();
        Long memberRoleId = sysUser.getMemberRoleId();
        List<Purchase> purchaseList;
        //判断是否代客下单
        if(customerMemberId != null && customerMemberId > 0){
            if(orderId != null && orderId > 0){
                purchaseList = purchaseRepository.findByMemberIdAndMemberRoleIdAndShopIdAndCustomerMemberIdAndCustomerMemberRoleIdAndOrderId(memberId, memberRoleId, shopId, customerMemberId, customerMemberRoleId, orderId);
            }else{
                purchaseList = purchaseRepository.findByMemberIdAndMemberRoleIdAndShopIdAndCustomerMemberIdAndCustomerMemberRoleId(memberId, memberRoleId, shopId, customerMemberId, customerMemberRoleId);
            }
        }else{
            purchaseList = purchaseRepository.findByMemberIdAndMemberRoleIdAndShopId(memberId, memberRoleId, shopId);
        }
        List<Long> commoditySkuIdList = purchaseList.stream().map(Purchase::getCommodityUnitPriceId).collect(Collectors.toList());
        //批量查询商品信息
        HashMap<Long, Commodity> commodityHashMap = new HashMap<>();
        List<Commodity> commodityList = commodityRepository.findByUnitPricePicListIdIn(commoditySkuIdList);
        commodityList.forEach(commodity -> {
            List<CommodityUnitPricePic> unitPricePicList = commodity.getUnitPricePicList();
            unitPricePicList.forEach(unitPricePic -> commodityHashMap.put(unitPricePic.getId(), commodity));
        });
        //过滤掉那些关联不到商品的进货单
        return (int) purchaseList.stream().map(Purchase::getCommodityUnitPriceId).map(commodityHashMap::get).filter(Objects::nonNull).count();
    }

    /**
     * 批量新增进货单
     * @return 是否成功
     */
    @Override
    public Boolean savePurchaseBatch(UserLoginCacheDTO sysUser, Long shopId, List<PurchaseRequest> purchaseRequestList) {
        Long memberId = sysUser.getMemberId();
        Long memberRoleId = sysUser.getMemberRoleId();
        List<Purchase> purchaseList = purchaseRequestList.stream().map(purchaseRequest -> {
            //检查商品规格
            Long commodityUnitPriceId = purchaseRequest.getCommodityUnitPriceId();
            Long setMealId = purchaseRequest.getSetMealId();
            Integer purchaseCommodityType = purchaseRequest.getPurchaseCommodityType();
            if (commodityUnitPriceId != null && commodityUnitPriceId > 0) {
                Commodity commodity = commodityRepository.findByUnitPricePicListId(commodityUnitPriceId);
                if (commodity != null) {
                    //区分是否套餐
                    Purchase oldPurchase;
                    if(setMealId != null && setMealId > 0){
                        oldPurchase = purchaseRepository.findFirstByMemberIdAndMemberRoleIdAndCommodityUnitPriceIdAndShopIdAndPurchaseCommodityTypeAndSetMealId(memberId, memberRoleId, commodityUnitPriceId, shopId, purchaseCommodityType, setMealId);
                    }else{
                        oldPurchase = purchaseRepository.findFirstByMemberIdAndMemberRoleIdAndCommodityUnitPriceIdAndShopIdAndPurchaseCommodityType(memberId, memberRoleId, commodityUnitPriceId, shopId, purchaseCommodityType);
                    }
                    if (oldPurchase != null) {
                        double count = oldPurchase.getCount() + purchaseRequest.getCount();
                        double stock = commodityService.getCommodityStockBySkuId(shopId, memberId, commodityUnitPriceId);
                        if(count <= stock) {
                            oldPurchase.setCount(count);
                        }else{
                            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_PASS_STOCK);
                        }
                    } else {
                        Integer purchaseMaxCount = Constants.PURCHASE_MAX_COUNT;
                        Integer existPurchaseCount = purchaseRepository.countByMemberIdAndMemberRoleIdAndShopId(memberId, memberRoleId, shopId);
                        if (existPurchaseCount >= purchaseMaxCount) {
                            throw new BusinessException(ResponseCode.PRODUCT_PURCHASE_COUNT_OUT);
                        }
                        double count = purchaseRequest.getCount();
                        double stock = commodityService.getCommodityStockBySkuId(shopId, memberId, commodityUnitPriceId);
                        if(count <= stock) {
                            oldPurchase = new Purchase();
                            //数据库持久化对象
                            oldPurchase.setShopId(shopId);
                            oldPurchase.setCount(purchaseRequest.getCount());
                            oldPurchase.setCommodityUnitPriceId(commodityUnitPriceId);
                            oldPurchase.setMemberId(memberId);
                            oldPurchase.setMemberName(sysUser.getCompany());
                            oldPurchase.setMemberRoleId(memberRoleId);
                            oldPurchase.setMemberRoleName(sysUser.getMemberRoleName());
                            oldPurchase.setUserId(sysUser.getUserId());
                            oldPurchase.setUserName(sysUser.getUserName());
                            oldPurchase.setPurchaseCommodityType(purchaseRequest.getPurchaseCommodityType());
                            oldPurchase.setSetMealId(purchaseRequest.getSetMealId());
                            oldPurchase.setSetMealName(purchaseRequest.getSetMealName());
                            oldPurchase.setIsMain(purchaseRequest.getIsMain());
                            oldPurchase.setParentSkuId(purchaseRequest.getParentSkuId());
                        }else{
                            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_PASS_STOCK);
                        }
                    }
                    return oldPurchase;
                } else {
                    throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
                }
            }else{
                throw new BusinessException(ResponseCode.PRODUCT_PURCHASE_UNITPRICE_NOT_EXIST);
            }
        }).collect(Collectors.toList());

        if(purchaseList.size() > 0){
            purchaseRepository.saveAll(purchaseList);
        }
        return true;
    }

    /**
     * 批量新增进货单
     * @return 是否成功
     */
    @Override
    public Boolean savePurchaseCustomerBatch(UserLoginCacheDTO sysUser, Long shopId, List<PurchaseCustomerRequest> purchaseRequestList) {
        Long memberId = sysUser.getMemberId();
        Long memberRoleId = sysUser.getMemberRoleId();
        List<Purchase> purchaseList = purchaseRequestList.stream().map(purchaseRequest -> {
            //检查商品规格
            Long commodityUnitPriceId = purchaseRequest.getCommodityUnitPriceId();
            Long setMealId = purchaseRequest.getSetMealId();
            Integer purchaseCommodityType = purchaseRequest.getPurchaseCommodityType();
            Long customerMemberId = purchaseRequest.getCustomerMemberId();
            Long customerMemberRoleId = purchaseRequest.getCustomerMemberRoleId();
            Long orderId = purchaseRequest.getOrderId();
            if (commodityUnitPriceId != null && commodityUnitPriceId > 0) {
                Commodity commodity = commodityRepository.findByUnitPricePicListId(commodityUnitPriceId);
                if (commodity != null) {
                    //查询库存
                    double stock;
                    //判断是否代客下单
                    if(customerMemberId != null && customerMemberId > 0){
                        stock = commodityService.getCommodityStockBySkuId(shopId, customerMemberId, commodityUnitPriceId);
                    }else{
                        stock = commodityService.getCommodityStockBySkuId(shopId, memberId, commodityUnitPriceId);
                    }
                    //区分是否套餐
                    Purchase oldPurchase;
                    if(setMealId != null && setMealId > 0){
                        //判断是否代客下单
                        if(customerMemberId != null && customerMemberId > 0){
                            if(orderId != null && orderId > 0){
                                oldPurchase = purchaseRepository.findFirstByMemberIdAndMemberRoleIdAndCommodityUnitPriceIdAndShopIdAndPurchaseCommodityTypeAndSetMealIdAndCustomerMemberIdAndOrderId(memberId, memberRoleId, commodityUnitPriceId, shopId, purchaseCommodityType, setMealId, customerMemberId, orderId);
                            }else{
                                oldPurchase = purchaseRepository.findFirstByMemberIdAndMemberRoleIdAndCommodityUnitPriceIdAndShopIdAndPurchaseCommodityTypeAndSetMealIdAndCustomerMemberId(memberId, memberRoleId, commodityUnitPriceId, shopId, purchaseCommodityType, setMealId, customerMemberId);
                            }
                        }else{
                            oldPurchase = purchaseRepository.findFirstByMemberIdAndMemberRoleIdAndCommodityUnitPriceIdAndShopIdAndPurchaseCommodityTypeAndSetMealId(memberId, memberRoleId, commodityUnitPriceId, shopId, purchaseCommodityType, setMealId);
                        }
                    }else{
                        oldPurchase = purchaseRepository.findFirstByMemberIdAndMemberRoleIdAndCommodityUnitPriceIdAndShopIdAndPurchaseCommodityType(memberId, memberRoleId, commodityUnitPriceId, shopId, purchaseCommodityType);
                    }
                    if (oldPurchase != null) {
                        double count = oldPurchase.getCount() + purchaseRequest.getCount();
                        if(count <= stock) {
                            oldPurchase.setCount(count);
                        }else{
                            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_PASS_STOCK);
                        }
                    } else {
                        Integer purchaseMaxCount = Constants.PURCHASE_MAX_COUNT;
                        Integer existPurchaseCount;
                        //判断是否代客下单
                        if(customerMemberId != null && customerMemberId > 0){
                            if(orderId != null && orderId > 0){
                                existPurchaseCount = purchaseRepository.countByMemberIdAndMemberRoleIdAndShopIdAndCustomerMemberIdAndCustomerMemberRoleIdAndOrderId(memberId, memberRoleId, shopId, customerMemberId, customerMemberRoleId, orderId);
                            }else{
                                existPurchaseCount = purchaseRepository.countByMemberIdAndMemberRoleIdAndShopIdAndCustomerMemberIdAndCustomerMemberRoleId(memberId, memberRoleId, shopId, customerMemberId, customerMemberRoleId);
                            }
                        }else{
                            existPurchaseCount = purchaseRepository.countByMemberIdAndMemberRoleIdAndShopId(memberId, memberRoleId, shopId);
                        }
                        if (existPurchaseCount >= purchaseMaxCount) {
                            throw new BusinessException(ResponseCode.PRODUCT_PURCHASE_COUNT_OUT);
                        }
                        double count = purchaseRequest.getCount();
                        if(count <= stock) {
                            oldPurchase = new Purchase();
                            //数据库持久化对象
                            oldPurchase.setShopId(shopId);
                            oldPurchase.setCount(purchaseRequest.getCount());
                            oldPurchase.setCommodityUnitPriceId(commodityUnitPriceId);
                            oldPurchase.setMemberId(memberId);
                            oldPurchase.setMemberName(sysUser.getCompany());
                            oldPurchase.setMemberRoleId(memberRoleId);
                            oldPurchase.setMemberRoleName(sysUser.getMemberRoleName());
                            oldPurchase.setUserId(sysUser.getUserId());
                            oldPurchase.setUserName(sysUser.getUserName());
                            oldPurchase.setPurchaseCommodityType(purchaseRequest.getPurchaseCommodityType());
                            oldPurchase.setSetMealId(purchaseRequest.getSetMealId());
                            oldPurchase.setSetMealName(purchaseRequest.getSetMealName());
                            oldPurchase.setIsMain(purchaseRequest.getIsMain());
                            oldPurchase.setParentSkuId(purchaseRequest.getParentSkuId());
                            oldPurchase.setCustomerMemberId(customerMemberId);
                            oldPurchase.setCustomerMemberRoleId(customerMemberRoleId);
                            oldPurchase.setOrderId(orderId);
                        }else{
                            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_PASS_STOCK);
                        }
                    }
                    return oldPurchase;
                } else {
                    throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
                }
            }else{
                throw new BusinessException(ResponseCode.PRODUCT_PURCHASE_UNITPRICE_NOT_EXIST);
            }
        }).collect(Collectors.toList());

        if(purchaseList.size() > 0){
            purchaseRepository.saveAll(purchaseList);
        }
        return true;
    }

    /**
     * 查询会员在商城的进货单里面商品的数量
     */
    @Override
    public Double getPurchaseCommodityCount(Long shopId, Long memberId, Long memberRoleId, Long commoditySkuId) {
        Purchase purchase = purchaseRepository.findFirstByMemberIdAndMemberRoleIdAndCommodityUnitPriceIdAndShopId(memberId, memberRoleId, commoditySkuId, shopId);
        if(purchase != null){
            return purchase.getCount();
        }else{
            return 0.0;
        }
    }
}

